package com.zyy;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @ProjectName: concurrent
 * @Package: com.zyy
 * @ClassName: NewThread
 * @Author: ZHAYUYAO
 * @Description: 如何创建线程
 * @Date: 2019/9/4 22:31
 * @Version: 1.0
 */
public class NewThread {

    /**
     * 方法1：继承Thread类
     */
    static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println("create Thread by extends Thread");
        }
    }

    /**
     * 方法2：实现Runnable接口
     */
    static class MyRunnable implements Runnable {

        @Override
        public void run() {
            System.out.println("create Thread by implements Runnable");

        }
    }

    /**
     * 方法3：实现Callable接口
     * 与实现Runnable接口区别：
     * 实现Runnable接口没有返回值
     * 现Callable接口允许有返回值
     */
    static class MyCallable implements Callable<String> {

        @Override
        public String call() throws Exception {
            System.out.println("create Thread by implements Callable");
            return "this is implements Callable return value";
        }
    }

    public static void main(String[] args) {
        //1
        Thread myThread = new MyThread();
        myThread.run();
        //2
        MyRunnable myRunnable = new MyRunnable();
        new Thread(myRunnable).run();
        //3
        try {
            MyCallable myCallable = new MyCallable();
            FutureTask futureTask = new FutureTask(myCallable);
            new Thread(futureTask).run();
            System.out.println(futureTask.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}
